package com.example.sqlliteapp;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
import org.json.JSONException;
import org.json.JSONArray;
import java.util.ArrayList;
import android.util.Log;
public class Activity2 extends AppCompatActivity {
    SQLite dbManager;
    long RecordID;
    String RecordTitle;
    String RecordDesc;
    String RecordDateRem;
    String RecordTimeRem;
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(getApplicationContext(),"欢迎回来!",Toast.LENGTH_SHORT).show();
        dbManager=new SQLite(this);
        getdatabaseinfo(1,"ignore");
        createNotificationChannel();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
        SearchView sv=(SearchView)menu.findItem(R.id.menu_search).getActionView();
        SearchManager sm=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
        sv.setSearchableInfo(sm.getSearchableInfo(getComponentName()));
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                getdatabaseinfo(2,query);
                return true;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                getdatabaseinfo(2,newText);
                return true;
            }
        });
        return true;
    }
    private void showChatDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_chat, null);
        builder.setView(dialogView);
        builder.setTitle("科大讯飞大模型");
        builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        final TextView chatHistory = dialogView.findViewById(R.id.chat_history);
        final EditText userInput = dialogView.findViewById(R.id.user_input);
        final Button sendButton = dialogView.findViewById(R.id.send_button);
        AlertDialog dialog = builder.create();
        final XunfeiApiClient apiClient = XunfeiApiClient.getInstance(this);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = userInput.getText().toString().trim();
                if (!message.isEmpty()) {
                    appendToChatHistory(chatHistory, "你: " + message);
                    userInput.setText("");
                    appendToChatHistory(chatHistory, "AI: 思考中...");
                    apiClient.sendMessage(message, new XunfeiApiClient.ApiCallback() {
                        @Override
                        public void onSuccess(final String response) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject json = new JSONObject(response);
                                        JSONArray choices = json.getJSONArray("choices");
                                        if (choices.length() > 0) {
                                            JSONObject firstChoice = choices.getJSONObject(0);
                                            JSONObject message = firstChoice.getJSONObject("message");
                                            String aiReply = message.getString("content");
                                            String currentText = chatHistory.getText().toString();
                                            currentText = currentText.replace("AI: 思考中...", "");
                                            chatHistory.setText(currentText);
                                            appendToChatHistory(chatHistory, "AI: " + aiReply);
                                        } else {
                                            appendToChatHistory(chatHistory, "AI: 未收到有效回复");
                                        }
                                    } catch (JSONException e) {
                                        appendToChatHistory(chatHistory, "AI: 回复解析错误: " + e.getMessage());
                                        Log.e("XunfeiAPI", "解析错误，完整响应: " + response);
                                    }
                                }
                            });
                        }
                        @Override
                        public void onFailure(final String error) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String currentText = chatHistory.getText().toString();
                                    currentText = currentText.replace("AI: 思考中...", "");
                                    chatHistory.setText(currentText);
                                    appendToChatHistory(chatHistory, "AI: 请求失败 - " + error);
                                }
                            });
                        }
                    });
                }
            }
        });
        dialog.show();
    }
    private void appendToChatHistory(TextView chatHistory, String message) {
        String currentText = chatHistory.getText().toString();
        if (!currentText.isEmpty()) {
            currentText += "\n\n";
        }
        chatHistory.setText(currentText + message);
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_help:
                AlertDialog.Builder info=new AlertDialog.Builder(this);
                info.setMessage("这是一个防止您遗忘的备忘录，您可以在这里记录您生活中的任何事情，并且可以设置闹钟来提醒您一些重要的事项")
                        .setTitle("时间备忘录APP简介")
                        .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .show();
                return true;
            case R.id.menu_settings:
                showChatDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    private void createNotificationChannel() {
        String CHANNEL_ID="ReminderID";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            channel.enableVibration(true);
            channel.setLightColor(Color.RED);
            channel.setVibrationPattern(new long[]{0});
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    ArrayList<Adapter> listnewsData = new ArrayList<Adapter>();
    MyCustomAdapter myadapter;
    public void getdatabaseinfo(int count1,String to_search){
        listnewsData.clear();
        Cursor cursor;
        if (count1==1) {
            cursor = dbManager.query(null, null, null, SQLite.ColID);
        }
        else{
            String[] SelectionsArgs={"%"+to_search+"%","%"+to_search+"%"};
            cursor = dbManager.query(null, "Title like ? or Description like ?", SelectionsArgs, SQLite.ColID);
        }
        if(cursor.moveToFirst()){
            do{
                listnewsData.add(new Adapter(cursor.getLong(cursor.getColumnIndex(SQLite.ColID)),
                        cursor.getString(cursor.getColumnIndex(SQLite.ColDateTime)),
                        cursor.getString(cursor.getColumnIndex(SQLite.ColTitle)),
                        cursor.getString(cursor.getColumnIndex(SQLite.ColDescription)),
                        cursor.getString(cursor.getColumnIndex(SQLite.ColRemTime)),
                        cursor.getString(cursor.getColumnIndex(SQLite.ColRemDate))));
            }while (cursor.moveToNext());
        }
        myadapter=new MyCustomAdapter(listnewsData);
        final ListView lsNews=(ListView)findViewById(R.id.lv_all);
        lsNews.setAdapter(myadapter);
    }
    public void update_element_new(){
        String title_received=RecordTitle;
        String description_received= RecordDesc;
        String RecordID_string=String.valueOf(RecordID);
        String time_rem_received=RecordTimeRem;
        String date_rem_received=RecordDateRem;
        Intent add_edit_act_intent=new Intent(getApplicationContext(), Activity1.class);
        add_edit_act_intent.putExtra("titlefrom",title_received);
        add_edit_act_intent.putExtra("descriptionfrom",description_received);
        add_edit_act_intent.putExtra("add_or_update","UPDATE");
        add_edit_act_intent.putExtra("recordno",RecordID_string);
        add_edit_act_intent.putExtra("rem_time",time_rem_received);
        add_edit_act_intent.putExtra("rem_date",date_rem_received);
        startActivityForResult(add_edit_act_intent,4);
}
    public void bu_add_edit_activity(View view) {
        RecordID=dbManager.RowCount()+1;
        String RecordID_string=String.valueOf(RecordID);
        Intent add_edit_act_intent1=new Intent(getApplicationContext(), Activity1.class);
        add_edit_act_intent1.putExtra("titlefrom","ignore");
        add_edit_act_intent1.putExtra("descriptionfrom","ignore");
        add_edit_act_intent1.putExtra("add_or_update","ADD");
        add_edit_act_intent1.putExtra("recordno",RecordID_string);
        add_edit_act_intent1.putExtra("rem_time","ignore");
        add_edit_act_intent1.putExtra("rem_date","ignore");
        startActivityForResult(add_edit_act_intent1,3);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==3)
        {
            getdatabaseinfo(1, "ignore");
            RecordID=0;
        }
        else if(requestCode==4){
            getdatabaseinfo(1, "ignore");
            RecordID=0;
        }
    }
    private class MyCustomAdapter extends BaseAdapter {
        public ArrayList<Adapter> listnewsDataAdpater ;
        public MyCustomAdapter(ArrayList<Adapter>  listnewsDataAdpater) {
            this.listnewsDataAdpater=listnewsDataAdpater;
        }
        @Override
        public int getCount() {
            return listnewsDataAdpater.size();
        }
        @Override
        public String getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        TextView txt_datetime;
        TextView txt_datetime_rem, txt_title, txt_desc;
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            LayoutInflater mInflater = getLayoutInflater();
            View myView = mInflater.inflate(R.layout.layout_ticket, null);
            final Adapter s = listnewsDataAdpater.get(position);
            String rem_DateTime=s.Date+" "+s.Time;
            txt_datetime_rem=(TextView)myView.findViewById(R.id.date_time_id_rem);
            if(s.Time.equalsIgnoreCase("notset")) {
                txt_datetime_rem.setVisibility(View.GONE);
            }
            else {
                txt_datetime_rem.setVisibility(View.VISIBLE);
                txt_datetime_rem.setText(rem_DateTime);
            }
            txt_title=(TextView)myView.findViewById(R.id.title_tv2);
            txt_title.setText(s.Title);
            txt_title.setSelected(true);
            txt_desc=(TextView)myView.findViewById(R.id.desc_tv2);
            txt_desc.setText(s.Description);
            txt_desc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RecordID=s.ID;
                    RecordTitle=s.Title;
                    RecordDesc=s.Description;
                    RecordDateRem=s.Date;
                    RecordTimeRem=s.Time;
                    update_element_new();
                }
            });
            return myView;
        }
    }
}